package com.primb.bench.project.search.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.primb.baselibs.util.FormatUtils;
import com.primb.baselibs.util.NetworkUtils;
import com.primb.baselibs.view.AutoCardView;
import com.primb.baselibs.view.AutoToolbar;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.dialog.ListDialog;
import com.primb.bench.common.module.repository.SearchDetailRepository;
import com.primb.bench.common.override.FitLayoutManager;
import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.common.utils.RoleLevelConvert;
import com.primb.bench.common.view.LineLayout;
import com.primb.bench.common.viewmodel.ViewIconKVEntity;
import com.primb.bench.project.approval.entity.NextPersonEntity;
import com.primb.bench.project.home.activity.LoanEnsureActivity;
import com.primb.bench.project.home.activity.LoanParameterActivity;
import com.primb.bench.project.home.entity.ApplyNextUserEntity;
import com.primb.bench.project.home.entity.ClientInfoEntity;
import com.primb.bench.project.home.entity.EnsureInfoEntity;
import com.primb.bench.project.home.entity.HttpApplyResultEntity;
import com.primb.bench.project.home.entity.HttpResultEntity;
import com.primb.bench.project.home.entity.LoanCalculateInfoEntity;
import com.primb.bench.project.home.entity.LoanInfoEntity;
import com.primb.bench.project.home.entity.LogoInfoEntity;
import com.primb.bench.project.home.entity.PromiseApplyEntity;
import com.primb.bench.project.home.entity.TaxInfoEntity;
import com.primb.bench.project.search.entity.ProcessEntity;
import com.primb.netlibs.exception.ApiException;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;


/**
 * Created by Chen on 2017/5/25.
 * 功能描述：
 */
public class SearchDetailActivity extends SwipeBaseActivity {

    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.tv_top)
    TextView tvTop;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.tv_logo_serial_number)
    TextView tvLogoSerialNumber;
    @BindView(R.id.tv_calculate_logo_protocol_number)
    TextView tvCalculateLogoProtocolNumber;
    @BindView(R.id.tv_calculate_logo_manager_name)
    TextView tvCalculateLogoManagerName;
    @BindView(R.id.tv_calculate_logo_manager_number)
    TextView tvCalculateLogoManagerNumber;
    @BindView(R.id.tv_calculate_logo_part)
    TextView tvCalculateLogoPart;
    @BindView(R.id.tv_calculate_logo_date)
    TextView tvCalculateLogoDate;
    @BindView(R.id.tv_add_customer)
    TextView tvAddCustomer;
    @BindView(R.id.tv_calculate_customer_name)
    TextView tvCalculateCustomerName;
    @BindView(R.id.tv_calculate_customer_number)
    TextView tvCalculateCustomerNumber;
    @BindView(R.id.tv_calculate_customer_type)
    TextView tvCalculateCustomerType;
    @BindView(R.id.tv_calculate_credit)
    TextView tvCalculateCredit;
    @BindView(R.id.tv_calculate_size)
    TextView tvCalculateSize;
    @BindView(R.id.tv_calculate_all_contribution)
    TextView tvCalculateAllContribution;
    @BindView(R.id.tv_calculate_used_contribution)
    TextView tvCalculateUsedContribution;
    @BindView(R.id.tv_calculate_contribution_number)
    TextView tvCalculateContributionNumber;
    @BindView(R.id.tv_calculate_is_contribution)
    TextView tvCalculateIsContribution;
    @BindView(R.id.tv_calculate_all_profit)
    TextView tvCalculateAllProfit;
    @BindView(R.id.tv_calculate_rate_adjust)
    TextView tvCalculateRateAdjust;
    @BindView(R.id.layout_customer_content)
    LinearLayout layoutCustomerContent;
    @BindView(R.id.layout_calculate_customer)
    CardView layoutCalculateCustomer;
    @BindView(R.id.tv_add_loan)
    TextView tvAddLoan;
    @BindView(R.id.tv_calculate_loan_money)
    TextView tvCalculateLoanMoney;
    @BindView(R.id.tv_calculate_loan_date)
    TextView tvCalculateLoanDate;
    @BindView(R.id.tv_calculate_loan_type)
    TextView tvCalculateLoanType;
    @BindView(R.id.tv_calculate_loan_business_type)
    TextView tvCalculateLoanBusinessType;
    @BindView(R.id.tv_calculate_loan_industry)
    TextView tvCalculateLoanIndustry;
    @BindView(R.id.tv_calculate_loan_rate_type)
    TextView tvCalculateLoanRateType;
    @BindView(R.id.layout_loan_content)
    LinearLayout layoutLoanContent;
    @BindView(R.id.layout_calculate_loan)
    CardView layoutCalculateLoan;
    @BindView(R.id.tv_add_ensure)
    TextView tvAddEnsure;
    @BindView(R.id.tv_calculate_ensure_main_type)
    TextView tvCalculateEnsureMainType;
    @BindView(R.id.tv_calculate_ensure_concreteness_type)
    TextView tvCalculateEnsureConcretenessType;
    @BindView(R.id.layout_ensure_money)
    LinearLayout layoutEnsureMoney;
    @BindView(R.id.layout_ensure_content)
    LinearLayout layoutEnsureContent;
    @BindView(R.id.layout_calculate_ensure)
    CardView layoutCalculateEnsure;
    @BindView(R.id.et_calculate_tax_vat)
    EditText etCalculateTaxVat;
    @BindView(R.id.tv_calculate_tax_income)
    TextView tvCalculateTaxIncome;
    @BindView(R.id.layout_tax_content)
    LinearLayout layoutTaxContent;
    @BindView(R.id.layout_calculate_tax)
    CardView layoutCalculateTax;
    @BindView(R.id.tv_calculate_result_all_cost_rate)
    TextView tvCalculateResultAllCostRate;
    @BindView(R.id.tv_calculate_result_change_cost_rate)
    TextView tvCalculateResultChangeCostRate;
    @BindView(R.id.tv_calculate_result_target_rate)
    TextView tvCalculateResultTargetRate;
    @BindView(R.id.tv_calculate_result_direct_rate)
    TextView tvCalculateResultDirectRate;
    @BindView(R.id.tv_calculate_result_reference_rate)
    TextView tvCalculateResultReferenceRate;
    @BindView(R.id.layout_result_content)
    CardView layoutResultContent;
    @BindView(R.id.tv_calculate_promise_list)
    TextView tvCalculatePromiseList;
    @BindView(R.id.et_calculate_promise_cash)
    EditText etCalculatePromiseCash;
    @BindView(R.id.tv_calculate_promise_rate)
    TextView tvCalculatePromiseRate;
    @BindView(R.id.tv_calculate_promise_start_date)
    TextView tvCalculatePromiseStartDate;
    @BindView(R.id.tv_calculate_promise_end_date)
    TextView tvCalculatePromiseEndDate;
    @BindView(R.id.tv_calculate_promise_deposit_day_now)
    TextView tvCalculatePromiseDepositDayNow;
    @BindView(R.id.tv_calculate_promise_deposit_day)
    TextView tvCalculatePromiseDepositDay;
    @BindView(R.id.tv_calculate_promise_deposit_sum_now)
    TextView tvCalculatePromiseDepositSumNow;
    @BindView(R.id.tv_calculate_promise_deposit_sum)
    TextView tvCalculatePromiseDepositSum;
    @BindView(R.id.tv_calculate_promise_basic_account)
    TextView tvCalculatePromiseBasicAccount;
    @BindView(R.id.tv_calculate_promise_settle_account)
    TextView tvCalculatePromiseSettleAccount;
    @BindView(R.id.tv_calculate_promise_salary_account)
    TextView tvCalculatePromiseSalaryAccount;
    @BindView(R.id.tv_calculate_promise_other_scene)
    TextView tvCalculatePromiseOtherScene;
    @BindView(R.id.tv_calculate_promise_other_scene_detail)
    TextView tvCalculatePromiseOtherSceneDetail;
    @BindView(R.id.tv_calculate_promise_remark)
    TextView tvCalculatePromiseRemark;
    @BindView(R.id.tv_calculate_promise_favorable_rate)
    TextView tvCalculatePromiseFavorableRate;
    @BindView(R.id.tv_calculate_promise_point)
    TextView tvCalculatePromisePoint;
    @BindView(R.id.layout_calculate_promise_detail)
    LinearLayout layoutCalculatePromiseDetail;
    @BindView(R.id.btn_calculate_promise)
    Button btnCalculatePromise;
    @BindView(R.id.layout_calculate_promise)
    CardView layoutCalculatePromise;
    @BindView(R.id.et_calculate_apply_rate)
    EditText etCalculateApplyRate;
    @BindView(R.id.et_calculate_apply_reason)
    EditText etCalculateApplyReason;
    @BindView(R.id.btn_calculate_apply)
    Button btnCalculateApply;
    @BindView(R.id.layout_calculate_apply)
    CardView layoutCalculateApply;
    @BindView(R.id.recycle_view_process)
    RecyclerView recycleViewProcess;
    @BindView(R.id.iv_calculate_customer_icon)
    ImageView ivCalculateCustomerIcon;
    @BindView(R.id.tv_calculate_is_contribution_parent)
    TextView tvCalculateIsContributionParent;
    @BindView(R.id.tv_calculate_all_profit_parent)
    TextView tvCalculateAllProfitParent;
    @BindView(R.id.tv_calculate_all_contribution_parent)
    TextView tvCalculateAllContributionParent;
    @BindView(R.id.tv_calculate_used_contribution_parent)
    TextView tvCalculateUsedContributionParent;
    @BindView(R.id.tv_calculate_contribution_number_parent)
    TextView tvCalculateContributionNumberParent;
    @BindView(R.id.tv_calculate_debt_parent)
    TextView tvCalculateDebtParent;
    @BindView(R.id.iv_calculate_loan_icon)
    ImageView ivCalculateLoanIcon;
    @BindView(R.id.btn_calculate_reapply)
    Button btnCalculateReapply;
    @BindView(R.id.tv_calculate_parent_contribution)
    ImageView tvCalculateParentContribution;
    @BindView(R.id.layout_parent_contribution)
    RelativeLayout layoutParentContribution;
    @BindView(R.id.layout_calculate_customer_parent)
    LinearLayout layoutCalculateCustomerParent;
    @BindView(R.id.btn_calculate_save)
    Button btnCalculateSave;
    @BindView(R.id.card_view_process)
    AutoCardView cardViewProcess;
    @BindView(R.id.layout_ensure_object)
    RelativeLayout layoutEnsureObject;
    @BindView(R.id.layout_logo_number)
    LinearLayout layoutLogoNumber;
    @BindView(R.id.tv_calculate_loan_repayment)
    TextView tvCalculateLoanRepayment;
    @BindView(R.id.layout_result_change_cost_rate)
    RelativeLayout layoutResultChangeCostRate;
    @BindView(R.id.line_result_change_cost_rate)
    View lineResultChangeCostRate;
    @BindView(R.id.layout_result_all_cost_rate)
    RelativeLayout layoutResultAllCostRate;
    @BindView(R.id.line_result_all_cost_rate)
    View lineResultAllCostRate;
    @BindView(R.id.layout_result_target_rate)
    RelativeLayout layoutResultTargetRate;
    @BindView(R.id.line_result_target_rate)
    View lineResultTargetRate;
    @BindView(R.id.tv_calculate_promise_delete)
    TextView tvCalculatePromiseDelete;
    @BindView(R.id.tv_calculate_logo_price_type)
    TextView tvCalculateLogoPriceType;
    @BindView(R.id.layout_logo_price_type)
    LinearLayout layoutLogoPriceType;
    @BindView(R.id.card_view_back_reason)
    CardView cvBackReason;
    @BindView(R.id.tv_back_reason)
    TextView tvBackReason;
    private ArrayList<ProcessEntity> dataList;
    private BaseQuickAdapter<ProcessEntity, BaseViewHolder> adapter;
    private CompositeSubscription subscription;
    private String priceId;
    private boolean isPrice;
    private boolean isReapply;
    private ListDialog listDialog;
    private LoanCalculateInfoEntity infoEntity;

    @Override
    protected void onBaseIntent() {
        super.onBaseIntent();
        Intent intent = getIntent();
        priceId = intent.getStringExtra("priceId");
        String priceType = intent.getStringExtra("priceType");
        isPrice = priceType.equals("02");
        isReapply = intent.getBooleanExtra("isReapply", false);
    }

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_search_detail;
    }

    @Override
    protected void onBaseBindView() {
        titleBar.setText("定价结果详细");
        toolBar.setNavigationOnClickListener(v -> SearchDetailActivity.this.finish());
        ivCalculateCustomerIcon.setVisibility(View.GONE);
        ivCalculateLoanIcon.setVisibility(View.GONE);
        tvCalculatePromiseDelete.setVisibility(View.INVISIBLE);
        FitLayoutManager layoutManager = new FitLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleViewProcess.setLayoutManager(layoutManager);
        recycleViewProcess.setItemAnimator(new DefaultItemAnimator());
        recycleViewProcess.setNestedScrollingEnabled(false);//嵌套scrollview
        dataList = new ArrayList<ProcessEntity>();
        adapter = new BaseQuickAdapter<ProcessEntity, BaseViewHolder>(R.layout.item_list_process, dataList) {
            @Override
            protected void convert(BaseViewHolder helper, ProcessEntity item) {
                LineLayout lineLayout = (LineLayout) helper.getView(R.id.layout_process_content_parent);
                if (getData().size() == 1) {
                    lineLayout.setDrawFooter(false);
                    lineLayout.setDrawHeader(false);
                } else if (helper.getAdapterPosition() == 0) {
                    lineLayout.setDrawHeader(false);
                    lineLayout.setDrawFooter(true);
                } else if (helper.getAdapterPosition() == getData().size() - 1) {
                    lineLayout.setDrawFooter(false);
                    lineLayout.setDrawHeader(true);
                } else {
                    lineLayout.setDrawFooter(true);
                    lineLayout.setDrawHeader(true);
                }
                helper.setText(R.id.tv_item_process_state, "审批状态：" + (item.getAppResult() != null ? item.getAppResult() : ""));
                setProcessState(item.getAppResult(), helper);
                String time = item.getAppTime().replace("&nbsp;", " ");
                helper.setText(R.id.tv_item_process_date, time.substring(0, time.length() - 2));
                helper.setText(R.id.tv_item_process_name, item.getAppUesr());
                helper.setText(R.id.tv_item_process_position, item.getAppPost());
                helper.setText(R.id.tv_item_process_content, item.getAppIdea());
            }
        };
        recycleViewProcess.setAdapter(adapter);
        if (isReapply) {
            btnCalculateReapply.setVisibility(View.VISIBLE);
        }

        etCalculateTaxVat.setEnabled(false);
    }

    private void setProcessState(String state, BaseViewHolder holder) {
        int mColor = Color.parseColor("#77d6f2");
        String stateRep = state.replace("已审批-", "");
        switch (stateRep) {
            case "发起":
                holder.setImageResource(R.id.iv_item_process_state, R.mipmap.process_apply_icon);
                holder.setVisible(R.id.iv_item_process_state, true);
                holder.setVisible(R.id.iv_item_process_reject, false);
                holder.setBackgroundRes(R.id.view_process_spot, R.drawable.shape_process_apply_spot);
                mColor = Color.parseColor("#77d6f2");
                holder.setBackgroundRes(R.id.layout_process_content, R.drawable.shape_process_start_bg);
                break;
            case "待审批":
                holder.setImageResource(R.id.iv_item_process_state, R.mipmap.process_wait_icon);
                holder.setVisible(R.id.iv_item_process_state, true);
                holder.setVisible(R.id.iv_item_process_reject, false);
                mColor = Color.parseColor("#666666");
                holder.setBackgroundRes(R.id.view_process_spot, R.drawable.shape_process_wait_spot);
                holder.setBackgroundRes(R.id.layout_process_content, R.drawable.shape_process_wait_bg);
                break;
            case "已审批-通过":
                holder.setImageResource(R.id.iv_item_process_state, R.mipmap.process_ok_icon);
                holder.setVisible(R.id.iv_item_process_state, true);
                holder.setVisible(R.id.iv_item_process_reject, false);
                holder.setBackgroundRes(R.id.view_process_spot, R.drawable.shape_process_ok_spot);
                mColor = Color.parseColor("#45bd88");
                holder.setBackgroundRes(R.id.layout_process_content, R.drawable.shape_process_ok_bg);
                break;
            case "已退回":
                holder.setImageResource(R.id.iv_item_process_state, R.mipmap.process_exit_icon);
                holder.setVisible(R.id.iv_item_process_state, true);
                holder.setVisible(R.id.iv_item_process_reject, false);
                holder.setBackgroundRes(R.id.view_process_spot, R.drawable.shape_process_exit_spot);
                mColor = Color.parseColor("#feca98");
                holder.setBackgroundRes(R.id.layout_process_content, R.drawable.shape_process_exit_bg);
                break;
            case "撤回":
                holder.setImageResource(R.id.iv_item_process_state, R.mipmap.process_back_icon);
                holder.setVisible(R.id.iv_item_process_state, true);
                holder.setVisible(R.id.iv_item_process_reject, false);
                holder.setBackgroundRes(R.id.view_process_spot, R.drawable.shape_process_back_spot);
                mColor = Color.parseColor("#b1b2f5");
                holder.setBackgroundRes(R.id.layout_process_content, R.drawable.shape_process_back_bg);
                break;
            case "再次提交":
                holder.setImageResource(R.id.iv_item_process_state, R.mipmap.process_reapply_icon);
                holder.setVisible(R.id.iv_item_process_state, true);
                holder.setVisible(R.id.iv_item_process_reject, false);
                holder.setBackgroundRes(R.id.view_process_spot, R.drawable.shape_process_apply_spot);
                mColor = Color.parseColor("#77d6f2");
                holder.setBackgroundRes(R.id.layout_process_content, R.drawable.shape_process_start_bg);
                break;
            case "否决":
                holder.setImageResource(R.id.iv_item_process_reject, R.mipmap.process_no_icon);
                holder.setVisible(R.id.iv_item_process_state, false);
                holder.setVisible(R.id.iv_item_process_reject, true);
                holder.setBackgroundRes(R.id.view_process_spot, R.drawable.shape_process_no_spot);
                mColor = Color.parseColor("#ff9eae");
                holder.setBackgroundRes(R.id.layout_process_content, R.drawable.shape_process_no_bg);
                break;
                default:
        }
//        holder.setTextColor(R.id.tv_item_process_position, mColor);
        holder.setTextColor(R.id.tv_item_process_state, mColor);
    }

    @Override
    protected void onLoadData() {
        showLoading();
        subscription = new CompositeSubscription();
        Subscription subscribe = SearchDetailRepository.getSearchPriceInfoEntity(priceId).subscribe(new HttpSubscriber<LoanCalculateInfoEntity>(this) {
            boolean isInfo = false;

            @Override
            public void onError(ApiException e) {
                showError(e.getMessage());
                hideLoading();
            }

            @Override
            public void onCompleted() {
                hideLoading();
            }

            @Override
            public void onNext(LoanCalculateInfoEntity object) {
                isInfo = true;
                infoEntity = object;
                showCalculateInfo(object);
                setInfoToPromise(object.getPromiseApplyEntity());

                dataList.clear();
                dataList.addAll(object.getProcessList());
                adapter.setNewData(dataList);
                if (dataList.size() > 0)
                    cardViewProcess.setVisibility(View.VISIBLE);
            }
        });
        subscription.add(subscribe);
    }

    public void setInfoToLogo(LogoInfoEntity entity) {
        tvLogoSerialNumber.setText(entity.getLogoNumber());
        tvCalculateLogoDate.setText(entity.getLogoDate());
        tvCalculateLogoManagerName.setText(entity.getLogoManagerName());
        tvCalculateLogoManagerNumber.setText(entity.getLogoManagerNum());
        tvCalculateLogoPart.setText(entity.getLogoPart());
        if (entity.getLogoProtocolNum() != null && !entity.getLogoProtocolNum().equals("")) {
            tvCalculateLogoProtocolNumber.setText(entity.getLogoProtocolNum());
            layoutLogoNumber.setVisibility(View.VISIBLE);
        } else {
            layoutLogoNumber.setVisibility(View.GONE);
        }
        layoutLogoPriceType.setVisibility(View.VISIBLE);
        tvCalculateLogoPriceType.setText(entity.getLogoPriceType());
    }

    public void setInfoToCustomer(ClientInfoEntity entity) {
        tvCalculateCustomerName.setText(entity.getCustomerName());
        tvCalculateCustomerNumber.setText(entity.getCustomerNum());
        tvCalculateCustomerType.setText(entity.getCustomerType());
        tvCalculateCredit.setText(entity.getCustomerCredit());
        tvCalculateSize.setText(entity.getCustomerSize());
        tvCalculateContributionNumber.setText(entity.getCustomerContributionNum());
        tvCalculateAllContribution.setText(entity.getCustomerAllContribution());
        tvCalculateIsContribution.setText(entity.getCustomerIsContribution());
        tvCalculateUsedContribution.setText(entity.getCustomerUsedContribution());
        tvCalculateRateAdjust.setText(entity.getCustomerAdjustRate());
        tvCalculateAllProfit.setText(entity.getCustomerAllProfit());

//        tvCalculateParentContribution.setBackgroundResource(entity.getCustomerIsContributionM().equals("0") ? R.mipmap.client_point_normal : R.mipmap.client_point_select);
//        layoutParentContribution.setVisibility(entity.getCustomerIsContributionM().equals("0") ? View.GONE : View.VISIBLE);
    }

    public void setInfoToLoan(LoanInfoEntity entity) {
        String loanMoney;
        try {
            loanMoney = FormatUtils.format2Int(entity.getLoanMoney());
        } catch (Exception e) {
            loanMoney = entity.getLoanMoney();
        }
        tvCalculateLoanMoney.setText(loanMoney);
        tvCalculateLoanDate.setText(entity.getLoanDate());
        tvCalculateLoanBusinessType.setText(entity.getLoanBusinessType());
        tvCalculateLoanType.setText(entity.getLoanType());
        tvCalculateLoanRepayment.setText(entity.getLoanRepayment());
        tvCalculateLoanIndustry.setText(entity.getLoanIndustry() == null || entity.getLoanIndustry().equals("") ? "-" : entity.getLoanIndustry());
        tvCalculateLoanRateType.setText(entity.getLoanRateType() == null || entity.getLoanRateType().equals("") ? "-" : entity.getLoanRateType());

    }

    public void setInfoToEnsure(EnsureInfoEntity entity) {
        tvCalculateEnsureMainType.setText(entity.getEnsureMainType());
        if (entity.getEnsureConcretenessType() != null && !TextUtils.isEmpty(entity.getEnsureConcretenessType()))
            tvCalculateEnsureConcretenessType.setText(entity.getEnsureConcretenessType());
        else
            tvCalculateEnsureConcretenessType.setText("-");
        layoutEnsureMoney.removeAllViews();
        layoutEnsureMoney.setVisibility(View.VISIBLE);
        layoutEnsureMoney.setBackgroundColor(ContextCompat.getColor(this, R.color.calculate_bg));
        boolean isImageView = false;
        if (!entity.getLnFinImpawnAmt().equals("0")) {
            new ViewIconKVEntity("金融质押品金额", entity.getLnFinImpawnAmt() + "").addView(this, layoutEnsureMoney, isImageView);
            isImageView = false;
        } else if (!entity.getLnAcctRecvAmt().equals("0")) {
            new ViewIconKVEntity("应收账款金额", entity.getLnAcctRecvAmt() + "").addView(this, layoutEnsureMoney, isImageView);
            isImageView = false;
        } else if (!entity.getLnPropertyAmt().equals("0")) {
            new ViewIconKVEntity("商业或居住用房地金额", entity.getLnPropertyAmt() + "").addView(this, layoutEnsureMoney, isImageView);
            isImageView = false;
        } else if (!entity.getLnOthMortAmt().equals("0")) {
            new ViewIconKVEntity("其它抵质押品金额", entity.getLnOthMortAmt() + "").addView(this, layoutEnsureMoney, isImageView);
            isImageView = false;
        } else if (!entity.getHighGuarantee().equals("0")) {
            new ViewIconKVEntity("优质保证金额", entity.getHighGuarantee() + "").addView(this, layoutEnsureMoney, isImageView);
            isImageView = false;
        } else if (!entity.getCommonGuarantee().equals("0")) {
            new ViewIconKVEntity("一般保证金额", entity.getCommonGuarantee() + "").addView(this, layoutEnsureMoney, isImageView);
            isImageView = false;
        } else {
            layoutEnsureMoney.setVisibility(View.GONE);
        }
        if (layoutEnsureMoney.getVisibility() == View.VISIBLE) {
            layoutEnsureObject.setVisibility(View.VISIBLE);
        } else {
            layoutEnsureObject.setVisibility(View.GONE);
        }
    }

    public void setInfoToTax(TaxInfoEntity entity) {
        String taxVat;
        String taxIncome;
        try {
            taxVat = (Double.valueOf(entity.getTaxVat()) * 100) + "";
            taxIncome = (Double.valueOf(entity.getTaxIncome()) * 100) + "";
        } catch (Exception e) {
            taxVat = entity.getTaxVat();
            taxIncome = entity.getTaxIncome();
        }
        etCalculateTaxVat.setText(FormatUtils.format(taxVat));
        tvCalculateTaxIncome.setText(FormatUtils.format(taxIncome));
//        etCalculateTaxVat.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
//        tvCalculateTaxIncome.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
    }

    public void showResultView(HttpResultEntity.DataBean bean) {
        try {
            if (AppConstant.ROLE_LEVEL_ENUM == RoleLevelConvert.RoleLevel.MANAGER) {
                layoutResultAllCostRate.setVisibility(View.GONE);
                layoutResultChangeCostRate.setVisibility(View.GONE);
                layoutResultTargetRate.setVisibility(View.GONE);

                lineResultAllCostRate.setVisibility(View.GONE);
                lineResultChangeCostRate.setVisibility(View.GONE);
                lineResultTargetRate.setVisibility(View.GONE);
            } else if (AppConstant.ROLE_LEVEL_ENUM == RoleLevelConvert.RoleLevel.DEPARTMENT) {
                layoutResultAllCostRate.setVisibility(View.VISIBLE);
                layoutResultChangeCostRate.setVisibility(View.GONE);
                layoutResultTargetRate.setVisibility(View.VISIBLE);

                lineResultAllCostRate.setVisibility(View.VISIBLE);
                lineResultChangeCostRate.setVisibility(View.GONE);
                lineResultTargetRate.setVisibility(View.VISIBLE);
            } else {
                layoutResultAllCostRate.setVisibility(View.VISIBLE);
                layoutResultChangeCostRate.setVisibility(View.VISIBLE);
                layoutResultTargetRate.setVisibility(View.VISIBLE);

                lineResultAllCostRate.setVisibility(View.VISIBLE);
                lineResultChangeCostRate.setVisibility(View.VISIBLE);
                lineResultTargetRate.setVisibility(View.VISIBLE);
            }

            tvCalculateResultAllCostRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpCostRate()) * 100));
            tvCalculateResultChangeCostRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpCostBdRate()) * 100));
            tvCalculateResultDirectRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpCustRate()) * 100));
            tvCalculateResultTargetRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpTargetRate()) * 100));
            tvCalculateResultReferenceRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpMarketIr()) * 100));
            tvCalculatePromiseRate.setText(FormatUtils.format(Double.valueOf(bean.getLnpTargetRate()) * 100));

            ivCalculateCustomerIcon.setVisibility(View.GONE);
            ivCalculateLoanIcon.setVisibility(View.GONE);
        } catch (NumberFormatException e) {
            showAlterDialogOne("提示", "测算结果数据格式异常，请联系管理员解决");
            return;
        }
    }

    public void setInfoToPromise(PromiseApplyEntity entity) {
        layoutCalculatePromiseDetail.setVisibility(View.VISIBLE);
        btnCalculatePromise.setVisibility(View.GONE);

        etCalculatePromiseCash.setText(FormatUtils.format(Double.valueOf(entity.getPromiseAdjustRate()) * 100));
        etCalculatePromiseCash.setEnabled(false);
        tvCalculatePromiseRate.setText(FormatUtils.format(Double.valueOf(entity.getPromiseAdjustDirectRate()) * 100));

        if (entity.isPromiseDetail()) {
            tvCalculatePromiseDepositDay.setText(entity.getPromiseDepositDay());
            tvCalculatePromiseDepositDayNow.setText(entity.getPromiseDepositDayNow());
            tvCalculatePromiseDepositSum.setText(entity.getPromiseDepositSum());
            tvCalculatePromiseDepositSumNow.setText(entity.getPromiseDepositSumNow());
            tvCalculatePromiseEndDate.setText(entity.getPromiseEndDate());
            tvCalculatePromiseStartDate.setText(entity.getPromiseStartDate());
            tvCalculatePromiseFavorableRate.setText(FormatUtils.format(Double.valueOf(entity.getPromiseFavorableRate()) * 100));
            tvCalculatePromiseOtherScene.setText(entity.getPromiseOtherScene());
            tvCalculatePromiseOtherSceneDetail.setText(entity.getPromiseOtherSceneDetail());
            tvCalculatePromisePoint.setText(entity.getPromisePoint());
            tvCalculatePromiseRemark.setText(entity.getPromiseRemark());
            tvCalculatePromiseSalaryAccount.setText((entity.isPromiseSalaryAccount() ? "" : "未") + "开立");
            tvCalculatePromiseSettleAccount.setText((entity.isPromiseSettleAccount() ? "" : "未") + "开立");
            tvCalculatePromiseBasicAccount.setText((entity.isPromiseBasicAccount() ? "" : "未") + "开立");
        } else {
            layoutCalculatePromiseDetail.setVisibility(View.GONE);
        }
        if (entity.isApply() && isPrice) {
            etCalculateApplyRate.setText(FormatUtils.format(Double.valueOf(entity.getApplyRate()) * 100));
            etCalculateApplyReason.setText(entity.getApplyReason().equals("") ? "无" : entity.getApplyReason());
            etCalculatePromiseCash.setEnabled(false);
        } else {
            layoutCalculateApply.setVisibility(View.GONE);
        }
    }

    public void showCalculateInfo(LoanCalculateInfoEntity entity) {
        tvAddCustomer.setVisibility(View.GONE);
        tvAddEnsure.setVisibility(View.GONE);
        tvAddLoan.setVisibility(View.GONE);
        layoutCalculateCustomer.setVisibility(View.VISIBLE);
        layoutCalculateLoan.setVisibility(View.VISIBLE);
        layoutCalculateEnsure.setVisibility(View.VISIBLE);
        layoutCalculateTax.setVisibility(View.VISIBLE);
        layoutCustomerContent.setVisibility(View.VISIBLE);
        layoutEnsureContent.setVisibility(View.VISIBLE);
        layoutLoanContent.setVisibility(View.VISIBLE);
        layoutTaxContent.setVisibility(View.VISIBLE);
        layoutResultContent.setVisibility(View.VISIBLE);
        btnCalculatePromise.setVisibility(View.GONE);
        layoutCalculatePromise.setVisibility(View.VISIBLE);
        if (entity.getPromiseApplyEntity().isPromiseDetail())
            layoutCalculatePromiseDetail.setVisibility(View.VISIBLE);
        btnCalculatePromise.setVisibility(View.GONE);
        btnCalculateApply.setVisibility(View.GONE);
        if (entity.getPromiseApplyEntity().isApply() && isPrice)
            layoutCalculateApply.setVisibility(View.VISIBLE);
        if (!isReapply) {
            etCalculateApplyRate.setEnabled(false);
            etCalculateApplyReason.setEnabled(false);
            btnCalculateReapply.setVisibility(View.GONE);
        } else {
            etCalculateApplyRate.setEnabled(true);
            etCalculateApplyReason.setEnabled(true);
            btnCalculateReapply.setVisibility(View.VISIBLE);
        }
        tvCalculatePromiseList.setVisibility(View.GONE);

        setInfoToLogo(entity.getLogoInfoEntity());
        setInfoToCustomer(entity.getClientInfoEntity());
        setInfoToLoan(entity.getLoanInfoEntity());
        setInfoToEnsure(entity.getEnsureInfoEntity());
        setInfoToTax(entity.getTaxInfoEntity());
        showResultView(entity.getResultInfoEntity());

        if (entity.getBackReason() != null && !TextUtils.isEmpty(entity.getBackReason())){
            cvBackReason.setVisibility(View.VISIBLE);
            tvBackReason.setText(entity.getBackReason());
        } else {
            cvBackReason.setVisibility(View.GONE);
        }
    }

    public void showLoading() {
        showLoadingDialog("加载中");
    }

    public void hideLoading() {
        hideLoadingDialog();
    }

    public void showError(String msg) {
        showToast(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscription != null) {
            subscription.clear();
        }
    }

    public void showPersonList(ApplyNextUserEntity entity, String applyRate) {
        listDialog = new ListDialog(this, entity.getData());
        listDialog.style(ListDialog.STYLE_TWO);
        listDialog.title("选择审批人");
        listDialog.btnNum(2);
        listDialog.content("111");
        listDialog.setOnItemClickL((bean, position) -> {
            String applyReason = etCalculateApplyReason.getText().toString();
            submitNextPerson(priceId, applyRate, applyReason, bean);
        });
        listDialog.setCancelable(false);
        listDialog.show();
    }

    private void submitNextPerson(String priceId, String applyRate, String applyReason, NextPersonEntity bean) {
        HashMap<String, String> map = new HashMap<>();
        map.put("priceId", priceId);
        map.put("approveRate", applyRate);
        map.put("applyLowPriceReason", applyReason);
        if (bean.getUserId() != null) {
            map.put("nextUsers", bean.getUserId());
        } else {
            map.put("nextUsers", "");
        }
        if (bean.getUserName() != null) {
            map.put("nextUserNames", bean.getUserName());
        } else {
            map.put("nextUserNames", "");
        }

        if (bean.getPhone() != null) {
            map.put("nextUserPhones", bean.getPhone());
        } else {
            map.put("nextUserPhones", "");
        }
        showLoading();
        Subscription subscribe = SearchDetailRepository.reapplyRate(map).subscribe(new HttpSubscriber<HttpApplyResultEntity>(this) {
            @Override
            public void onError(ApiException e) {
                showError(e.getMessage());
                hideLoading();
            }

            @Override
            public void onCompleted() {
                hideLoading();
            }

            @Override
            public void onNext(HttpApplyResultEntity httpApplyResultEntity) {
                if (httpApplyResultEntity.getSuccess().equals("true")) {
                    intentToBack();
                    showError("审批人选择成功");
                } else {
                    showError(httpApplyResultEntity.getMsg());
                }
            }
        });
        subscription.add(subscribe);
    }

    private void intentToBack() {
        setResult(AppConstant.SEARCH_REAPPLY_RESULT);
        this.finish();
    }


    public void reapply() {
        if (!NetworkUtils.isNetworkConnected(this)) {
            showError("无网络连接，请连接网络后重试");
            return;
        }

        if (etCalculateApplyRate.getText().toString().equals("")) {
            showError("申请利率不能为空");
            return;
        }
        String applyRate;
        try {
            applyRate = FormatUtils.format(Double.valueOf(etCalculateApplyRate.getText().toString()) / 100);
        } catch (Exception e) {
            showError("申请利率格式异常");
            return;
        }
        String applyReason = etCalculateApplyReason.getText().toString();
        showLoading();
        Subscription subscribe = SearchDetailRepository.reapplyNextList(priceId, applyRate, applyReason).subscribe(new HttpSubscriber<ApplyNextUserEntity>(this) {
            @Override
            public void onError(ApiException e) {
                showError(e.getMessage());
                hideLoading();
            }

            @Override
            public void onCompleted() {
                hideLoading();
            }

            @Override
            public void onNext(ApplyNextUserEntity entity) {
                showPersonList(entity, applyRate);
            }
        });
        subscription.add(subscribe);
    }

    public void intentToParameter(HttpResultEntity.DataBean bean) {
        Intent intent = new Intent(this, LoanParameterActivity.class);
        intent.putExtra("info", bean);
        startActivity(intent);
    }

    @OnClick({R.id.layout_ensure_object, R.id.btn_calculate_reapply, R.id.tv_calculate_result_parameter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_ensure_object:
                Intent intent = new Intent(SearchDetailActivity.this, LoanEnsureActivity.class);
                intent.putExtra("isEdit", false);
                intent.putExtra("priceId", priceId);
                intent.putExtra("isView", true);
                startActivity(intent);
                break;
            case R.id.btn_calculate_reapply:
                reapply();
                break;
            case R.id.tv_calculate_result_parameter:
                if (infoEntity.getResultInfoEntity() == null) {
                    showError("定价测算的结果为空");
                    return;
                }
                intentToParameter(infoEntity.getResultInfoEntity());
                break;
        }
    }

}
